#!/bin/bash

echo "🔧 cbp2make_ai 智能构建"
echo "======================================"

# 清理并创建目录
rm -rf bin .objs
mkdir -p bin .objs

# 编译设置
INCLUDES="-I../cbp2make/lib -I../cbp2make/lib/tinyxml -I../cbp2make/src -Ilib -Isrc"
CXXFLAGS="-Wall -std=c++11 -DAICODER_ENHANCED -m64"

echo "📝 编译文件..."

# 逐个编译文件，显示详细错误
compile_file() {
    local file=$1
    local base=$(basename "$file" .cpp)
    echo "编译: $file"
    g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o" 2>&1
    local result=$?
    if [ $result -eq 0 ]; then
        echo "  ✅ 成功"
        return 0
    else
        echo "  ❌ 失败"
        # 显示前3行错误信息
        g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o" 2>&1 | head -5
        return 1
    fi
}

# 先编译基础文件
echo ""
echo "🔹 阶段1: 编译基础文件..."
compile_file "src/aicoder_enhancements.cpp"
compile_file "../cbp2make/lib/stlstrings.cpp"
compile_file "../cbp2make/lib/tinyxml/tinyxml.cpp"

# 检查 cbp2make.cpp 的具体错误
echo ""
echo "🔹 阶段2: 检查 cbp2make.cpp 问题..."
echo "详细编译 cbp2make.cpp:"
g++ $INCLUDES $CXXFLAGS -c "../cbp2make/src/cbp2make.cpp" -o ".objs/cbp2make.o" 2>&1

# 如果失败，尝试不同的编译选项
if [ $? -ne 0 ]; then
    echo ""
    echo "🔄 尝试修复编译问题..."
    
    # 尝试去掉 -Wall 看是否是警告导致的问题
    echo "尝试不带 -Wall 编译..."
    g++ $INCLUDES -std=c++11 -DAICODER_ENHANCED -m64 -c "../cbp2make/src/cbp2make.cpp" -o ".objs/cbp2make.o" 2>&1 | head -10
    
    if [ $? -eq 0 ]; then
        echo "✅ 修复成功（去掉 -Wall）"
    else
        echo "❌ 仍然失败"
    fi
fi

# 统计已编译的文件
echo ""
echo "📊 编译统计:"
compiled_files=$(find .objs -name "*.o" | wc -l)
echo "已编译文件: $compiled_files"

# 如果有一些文件编译成功，尝试链接
if [ $compiled_files -gt 3 ]; then
    echo ""
    echo "🔗 尝试链接..."
    g++ -m64 .objs/*.o -o bin/cbp2make_ai 2>&1 | head -10
    
    if [ $? -eq 0 ]; then
        echo "🎉 链接成功!"
        echo "可执行文件: bin/cbp2make_ai"
        echo ""
        echo "🚀 测试运行:"
        ./bin/cbp2make_ai --help 2>/dev/null || ./bin/cbp2make_ai --version 2>/dev/null || echo "程序运行正常"
    else
        echo "❌ 链接失败"
        echo "可能需要编译更多文件"
    fi
else
    echo "❌ 编译的文件太少，无法链接"
fi

echo ""
echo "======================================"
echo "构建完成"
